<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <view
      class="ultraman-container"
      :style="{
        backgroundImage: `url(${oss2('others/2023Q4Code/Q4_bg.png')})`,
      }"
    >
      <view
        class="input_content"
        :style="{
          backgroundImage: `url(${oss2('others/2023Q4Code/DH_pic.png')})`,
        }"
      >
      </view>

      <view
        class="input_box_bg"
        :style="{
          backgroundImage: `url(${oss2('others/2023Q4Code/input_bg.png')})`,
        }"
      >
        <input
          @focus="focusInput"
          @change="inputChange"
          v-model="code"
          placeholder="请输入字符串"
          placeholder-style="color: rgba(1, 0, 1,0.2);"
        />
        <view
          class="search_icon"
          :style="{
            backgroundImage: `url(${oss2('others/2023Q4Code/input_icon.png')})`,
          }"
        >
        </view>
      </view>

      <view class="bottom_btn items-center">
        <view
          @click="cancelBtn"
          :style="{
            backgroundImage: `url(${oss2('others/2023Q4Code/cancel_btn.png')})`,
          }"
        ></view>

        <view
          @click="scanCode"
          :style="{
            backgroundImage: `url(${oss2(
              'others/2023Q4Code/confirm_btn.png'
            )})`,
          }"
        ></view>
      </view>
    </view>

    <!-- 弹窗 -->
    <view class="mode" v-if="showDialog">
      <view
        class="Dialog_body w-295px top-21vh left-41px"
        :style="{
          backgroundImage: `url(${oss2('others/2023Q4Code/' + dialogBg)})`,
        }"
      >
        <view
          class="Dialog_close"
          :style="{
            backgroundImage: `url(${oss2('others/2023Q4Code/close_icon.png')})`,
          }"
          @click.stop="dialogClose"
        ></view>
        <view
          class="Dialog_back w-112px h-36px bottom-48px left-91px"
          @click.stop="dialogBack"
          :style="{
            backgroundImage: `url(${oss2('others/2023Q4Code/back_icon.png')})`,
          }"
        ></view>
        <view class="Dialog_text">
          有任何问题请拨打客服热线
          <button class="number" @click="PhoneCall">400-0880-325</button>
        </view>
      </view>
    </view>

    <!-- 活动规则弹窗 -->
    <!-- <rule-popup v-if="showRule" :ruleType="ruleType" @close="closeRule" /> -->
  </scroll-view>
</template>

    <script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, generateSign2, message } from "@/utils/utils";
// import RulePopup from "@/components/Q4-popup.vue";
import { userLogin } from "@/services/utils";
let enterTime = "";
let outTime = "";
let stayTime = "";
let scanStauts = {
  4001: { img: "code_wait.png", close: "error_unactive", back: "error_back2" },
  4002: { img: "code_past.png", close: "error_redeemed", back: "error_back3" },
  4000: {
    img: "code_input_err.png",
    close: "error_QRcode",
    back: "error_back1",
  },
};

const locationInfo = ref({ latitude: "", longitude: "" });
const code = ref("");
// const showRule = ref(false);
// const ruleType = ref("rule");
const showDialog = ref(false);
const dialogCode = ref(0);
const dialogBg = ref("");

onLoad(async (query) => {
  const pages = getCurrentPages();
  const beforePage = pages[pages.length - 2]?.route ?? "";
  // 从会员页返回
  if (beforePage === "campaign/pages/oreoQ4/scanCodeInput" && query.code) {
    console.log("===========返回携带code", query.code);
    code.value = query.code;
    uni.getLocation({
      type: "gcj02",
      success(res) {
        locationInfo.value.latitude = res.latitude;
        locationInfo.value.longitude = res.longitude;
      },
      complete() {
        const body = {
          userValue: uni.getStorageSync("OPENID"),
          qrCode: code.value,
          source: "Q4",
          timestamp: Date.parse(new Date()),
          lng: locationInfo.value.longitude,
          lat: locationInfo.value.latitude,
        };
        scanCodeIn(body);
      },
    });
  }
});
onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
});
onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;

  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "view",
    "redeem_page",
    stayTime
  );
});
onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "view",
    "redeem_page",
    stayTime
  );
});

const linkTo = (url) => uni.navigateTo({ url });

const scanCode = () => {
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "click",
    "check_code",
    ""
  );

  if (code.value === "") return message("请输入字符串!");

  // 判断会员
  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    uni.navigateTo({
      url: "/pages/vip/register?tag=Q4&from=input&code=" + code.value,
    });
    return;
  }

  uni.getLocation({
    type: "gcj02",
    success(res) {
      locationInfo.value.latitude = res.latitude;
      locationInfo.value.longitude = res.longitude;
    },
    complete() {
      const body = {
        userValue: uni.getStorageSync("OPENID"),
        qrCode: code.value,
        source: "Q4",
        timestamp: Date.parse(new Date()),
        lng: locationInfo.value.longitude,
        lat: locationInfo.value.latitude,
      };
      scanCodeIn(body);
    },
  });
};
const scanCodeIn = async (body) => {
  uni.request({
    url: `${process.env.Q4_URL}/zex-qr/api/qr/validation`,
    method: "get",
    data: {
      ...body,
      ...{ sign: generateSign2(body) },
    },

    success: async (requestRes) => {
      getApp()
        .getUserInfo()
        .then((user) => {
          if (requestRes.data.code === 200) {
            linkTo(
              `/campaign/pages/oreoQ4/webview?source=index&accesstoken=${uni.getStorageSync(
                "TOKEN"
              )}&code=${code.value}&openid=${uni.getStorageSync(
                "OPENID"
              )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                user.memberScore.memberId
              }&agree=${uni.getStorageSync("Q4AGREE")}&latitude=${
                locationInfo.value.latitude ? locationInfo.value.latitude : ""
              }&longitude=${
                locationInfo.value.longitude ? locationInfo.value.longitude : ""
              }`
            );
            code.value = "";
          } else if ([4000].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4000;
            dialogBg.value = scanStauts[4000].img;
            showDialog.value = true;
          } else if ([4001].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4001;
            dialogBg.value = scanStauts[4001].img;
            showDialog.value = true;
          } else if ([4002].includes(requestRes.data.code)) {
            code.value = "";
            dialogCode.value = 4002;
            dialogBg.value = scanStauts[4002].img;
            showDialog.value = true;
          } else {
            code.value = "";
            uni.showToast({
              title: requestRes.data.message,
              icon: "none",
              duration: 2000,
            });
          }
        });
    },
    fail(requestErr) {
      code.value = "";
      uni.showToast({
        title: requestErr.data.message,
        icon: "none",
        duration: 2000,
      });
    },
  });
};

const focusInput = () => {
  getApp().emdlz2(
    "track",
    "event",
    "ultraman_campaign_manual_redeem",
    "click",
    "input_code",
    ""
  );
};
const inputChange = () => {
  console.log("wwwwwww", code.value);
};
const cancelBtn = () => {
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "click",
    "cancel_redeem",
    ""
  );
  uni.navigateBack({
    delta: 1,
  });
};
const dialogClose = () => {
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "click",
    scanStauts[dialogCode.value].close,
    ""
  );
  showDialog.value = false;
};
const dialogBack = () => {
  getApp().emdlz2(
    "track",
    "event",
    "q4_onecodecampaign_redeem_page",
    "click",
    scanStauts[dialogCode.value].back,
    ""
  );
  showDialog.value = false;
};

const PhoneCall = () => {
  getApp().emdlz2(
    "track",
    "event",
    "pandas_campaign_wish_rule_page",
    "click",
    "contact_customer_service_phone",
    ""
  );
  uni.makePhoneCall({
    phoneNumber: "400-0880-325",
  });
};
// const closeRule = () => {
//   getApp().emdlz2(
//     "track",
//     "event",
//     "q4_onecodecampaign_landing_page",
//     "click",
//     "close_rules",
//     ""
//   );

//   showRule.value = false;
// };

onShareAppMessage((e) => {
  const shareObj = {
    title: "一起参加现金红包抽奖活动", // 默认是小程序的名称(可以写slogan等)
    path: "/pages/2023oreocore/index?from=pubid:shareback;aid:sharecard", // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/2023Q4Code/Q4share.jpg"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

    <style>
page {
  background-color: #02071e !important;
}
</style>
    <style lang="less" scoped>
.ultraman-container {
  position: relative;
  width: 100%;
  min-height: 724px;
  height: 100vh;
  background-color: #08204e;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 784px;

  .input_content {
    position: absolute;
    top: 63px;
    left: 43px;
    width: 290px;
    height: 447px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 290px 100%;
  }

  .input_box_bg {
    position: absolute;
    top: 495px;
    left: 43px;
    width: 290px;
    height: 55px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 290px 100%;
    box-sizing: border-box;
    padding: 15px 28px;
    input {
      width: 204px;
      height: 25px;
      background: #ffffff;
      border-radius: 16px;
      box-sizing: border-box;
      padding: 0 7px;
      font-size: 15px;
      font-family: Yuanti SC;
      font-weight: 400;
      color: #575757;
    }
    .search_icon {
      width: 26px;
      height: 24px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 26px 100%;
      position: absolute;
      top: 15px;
      right: 28px;
    }
  }
  .bottom_btn {
    position: absolute;
    left: 0;
    top: 565px;
    width: 100%;
    height: 70px;
    box-sizing: border-box;
    padding: 0 30px;
    display: flex;
    justify-content: space-between;
    view {
      width: 157px;
      height: 70px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 157px 100%;
    }
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.7);

  .Dialog_body {
    position: absolute;
    height: 246px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_close {
      position: absolute;
      top: 18px;
      right: 21px;
      width: 36px;
      height: 36px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_back {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_text {
      position: absolute;
      bottom: 18px;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 10px;
      line-height: 10px;
      font-size: 10px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #0041c0;
      .number {
        width: 74px;
        background-color: transparent;
        margin: 0;
        padding: 0;
        line-height: 24px;
        font-size: 9px;
        color: #06bbf6;
        &::after {
          border: none;
        }
      }
    }
  }
}
</style>
